package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;
 //添加好友
    public void save(Long userId, Long id) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(id);
        Query query1 = Query.query(criteria1);
        //判断是否存在
        if (!mongoTemplate.exists(query1, Friend.class)) {
            Friend friend1 = new Friend();
            friend1.setCreated(System.currentTimeMillis());
            friend1.setUserId(userId);
            friend1.setFriendId(id);
            mongoTemplate.save(friend1);
        }
        Criteria criteria2 = Criteria.where("userId").is(id).and("friendId").is(userId);
        Query query2 = Query.query(criteria2);
        if (!mongoTemplate.exists(query2,Friend.class)){
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(id);
            friend2.setFriendId(userId);
            mongoTemplate.save(friend2);

        }


    }

    //查询好友
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page-1)*pagesize);
        List<Friend> list = mongoTemplate.find(query, Friend.class);

        return list;
    }
}
